package middol.upload.utils

import grails.gorm.transactions.Transactional
import groovy.util.logging.Slf4j
import middol.global.BusinessException
import middol.base.FileInfo
import middol.config.UploadCfg
import middol.constants.i18n.CommonConstants
import middol.result.Result
import middol.result.ResultUtils
import middol.upload.IFileInfo
import middol.utils.LangService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile
import java.text.SimpleDateFormat

/**
* @Description:    本地文件操作工具类
* @Author:         zhangjiayu@middol.com
* @CreateDate:     2020/10/22 13:49
* @Version:        1.0
*/
@Slf4j
@Component
class LocalUtils {
    @Autowired
    LangService langService

    @Autowired
    UploadCfg uploadCfg

    /**
     * 单个文件上传
     * @param f             附件
     * @param fileInfo      附件其他信息
     * @return
     */
    @Transactional
    Result singleUpload(MultipartFile f, IFileInfo fileInfo) {
        log.debug("开始上传附件。。。。。")
        String rootDir = uploadCfg?.rootDir
        try {
            if (f.getSize() > 0) {
                String fileName = f.getOriginalFilename()                            // 获取文件名称
                String fileType
                if (fileName != null && fileName != '') {
                    fileType = fileName[fileName.indexOf(".")..fileName.length() - 1]  // 获取文件类型
                }
                String dirPath = rootDir + fileInfo.dirPath?.replace('\\', '/')
                File dir = new File(dirPath)
                if (!dir.exists()) {
                    dir.mkdirs()
                }                                                                    // 生成新的文件名 原文件名+时间戳
                def newFileName = fileName.substring(0, fileName.indexOf('.')) + "_" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + fileType
                def filePath = dirPath + "/" + newFileName

                File file = new File(filePath)
                f.transferTo(file)
                // 存入对应文件夹，将文件信息存入数据库
                def fi = new FileInfo(fileName: fileName, path: filePath, module: dirPath, url: filePath, moduleId: fileInfo.moduleId, name: fileName, size: f.getSize())
                fi.save(flush: true)
                return ResultUtils.ok(fi)
            }else{
                throw new BusinessException(langService.getMessage(CommonConstants.FILE_UPLOAD_ISNULL))
            }
        } catch (e) {
            e.printStackTrace()
            def msg = langService.getMessage(CommonConstants.FILE_UPLOAD_ERROR, e.message)
            log.error("上传文件出错", e.message)
            throw new BusinessException(msg)
        }
    }

    /**
     * 附件列表上传
     * @param fileInfo
     * @return
     */
    List<Result> multiUpload(IFileInfo fileInfo){
        def list = []
        fileInfo?.fileList?.each{ fItem ->
            list << singleUpload(fItem, fileInfo)
        }
        return list
    }
}
